package cn.fancy.sdk.floatwindow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.fancy.sdk.common.utils.ResUtil;

public class FloatWindowActivityDetail extends Activity implements
		OnClickListener {
    private static final int INPUT_FILE_REQUEST_CODE = 1;
	private static final int INPUT_FILE_REQUEST_CODE_Android4 = 2;
    private static final String TAG = FloatWindowActivityDetail.class.getSimpleName();
    private ValueCallback<Uri[]> mUploadMessage;
    private ValueCallback<Uri> mUploadMessage4;
    private String mCameraPhotoPath = null;
    private long size = 0;

	private WebView mWebView;
	private ProgressBar mProgressBar;
	private TextView mTitleBack, mTitleRefresh, mTitleClose;

	private Uri fileUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.e(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(ResUtil
				.getLayoutId(this, "fancy_floatweb_activitydetail"));
		//设置自动旋转
		/*MyOrientoinListener myOrientoinListener=new MyOrientoinListener(this);
		boolean autoRotateOn = (Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
		if (autoRotateOn) {
			myOrientoinListener.enable();
		}*/

		mWebView = (WebView) findViewById(ResUtil.getId(this,
				"float_activitydetail_webview"));
		mTitleBack = (TextView) findViewById(ResUtil.getId(this,
				"float_activitydetail_back"));
		mTitleRefresh = (TextView) findViewById(ResUtil.getId(this,
				"float_activitydetail_refresh"));
		mTitleClose = (TextView) findViewById(ResUtil.getId(this,
				"float_activitydetail_close"));
		mProgressBar = (ProgressBar) findViewById(ResUtil.getId(this,
				"float_activitydetail_progressbar"));

		initWebView();

		mTitleBack.setOnClickListener(this);
		mTitleRefresh.setOnClickListener(this);
		mTitleClose.setOnClickListener(this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.e(TAG, "onResume");

	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView() {
		Log.e(TAG, "initWebView");
		Intent intent=getIntent();
		String url=intent.getStringExtra("custombrowserurl");
//		String url = "http://www.baidu.com/";
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		mWebView.getSettings().setAppCacheEnabled(false);
		mWebView.getSettings().setDatabaseEnabled(false);
		mWebView.getSettings().setDomStorageEnabled(false);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		mWebView.getSettings().setSupportZoom(true);
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		mWebView.getSettings().setLoadWithOverviewMode(true);
		mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
		mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		// mWebView.setDownloadListener(new QCDownloadListener());

		// 设置缓存，减少打开悬浮的loading时间
		mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
		String appCacheDir = this.getApplicationContext()
				.getDir("fancy_cache", Context.MODE_PRIVATE).getPath();
		mWebView.getSettings().setAppCachePath(appCacheDir);
		mWebView.getSettings().setAllowFileAccess(true);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		// mWebView.addJavascriptInterface(new JSInterface(), "Cfloatwindow");
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.e(TAG, "shouldOverrideUrlLoading");
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				Log.e(TAG, "onPageFinished");
			}
		});

		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				Log.e(TAG, "onProgressChanged");
				if (newProgress == 100) {
					mProgressBar.setVisibility(View.GONE);
				} else {
					mProgressBar.setVisibility(View.VISIBLE);// 开始加载网页时显示进度条
					mProgressBar.setProgress(newProgress);// 设置进度值
				}
			}

			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
										String acceptType, String capture) {
			    Log.e(TAG, "android 4.1 openFileChooser");
				// Double check that we don't have any existing callbacks
				if (mUploadMessage4 != null) {
					mUploadMessage4.onReceiveValue(null);
				}
				mUploadMessage4 = uploadMsg;
				Log.e("FileCooserParams => ", uploadMsg.toString());

				openCameraOrAlbum(INPUT_FILE_REQUEST_CODE_Android4);
            }

			@Override
			public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
				Log.e(TAG, "onShowFileChooser");
				// Double check that we don't have any existing callbacks
				if (mUploadMessage != null) {
					mUploadMessage.onReceiveValue(null);
				}
				mUploadMessage = filePath;
				Log.e("FileCooserParams => ", filePath.toString());

				openCameraOrAlbum(INPUT_FILE_REQUEST_CODE);

				return true;
			}

		});
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setLoadsImagesAutomatically(true);

		mWebView.loadUrl(url);
	}

	private void openCameraOrAlbum(int resqCode) {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		fileUri = Uri.fromFile(createImageFile());
		Log.e(TAG, fileUri.getPath());
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
		contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
		contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
		contentSelectionIntent.setType("image/*");

		Intent[] intentArray = new Intent[]{takePictureIntent};

		Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
		chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
		chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
		chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
		startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), resqCode);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == ResUtil.getId(this, "float_activitydetail_back")) {
			Log.e(TAG, "float_activitydetail_back");
			mWebView.goBack();
		} else if (v.getId() == ResUtil.getId(this,
				"float_activitydetail_refresh")) {
			Log.e(TAG, "float_activitydetail_refresh");
			mWebView.reload();
		} else if (v.getId() == ResUtil.getId(this,
				"float_activitydetail_close")) {
			Log.e(TAG, "float_activitydetail_close");
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.e(TAG, "onKeyDown");
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e(TAG, "onActivityResult");

		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == INPUT_FILE_REQUEST_CODE) {
			Uri[] results;
			if (data != null) {
				results = new Uri[]{Uri.parse(data.getDataString())};
			} else if (fileUri != null) {
				File imageFile = new File (fileUri.getPath());
				Uri resUri = Uri.fromFile(imageFile);
				results = new Uri[] {resUri};
			} else {
				results = new Uri[]{Uri.EMPTY};
			}

			mUploadMessage.onReceiveValue(results);
			mUploadMessage = null;
		} else if (requestCode == INPUT_FILE_REQUEST_CODE_Android4) {
			Uri result = Uri.EMPTY;
			if (data != null) {
//				result = data.getData();
				ClipData clipData = data.getClipData();
				if (clipData != null) {
					result = clipData.getItemAt(0).getUri();
				} else {
					result = data.getData();
				}
			} else if (fileUri != null) {
				File imageFile = new File(fileUri.getPath());
				result = Uri.fromFile(imageFile);
			} else {
				result = Uri.EMPTY;
			}

			mUploadMessage4.onReceiveValue(result);
			mUploadMessage4 = null;
		}

	}

	private File createImageFile(){
		File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), getPackageName());

		if (!directory.exists()) {
			if (!directory.mkdirs()) {
				Log.e(TAG, "Failed to create storage directory.");
				return null;
			}
		}

		String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new Date());

		return new File(directory.getPath() + File.separator + "IMG_"
				+ timeStamp + ".jpg");
	}

    /*class MyOrientoinListener extends OrientationEventListener {

        public MyOrientoinListener(Context context) {
            super(context);
        }

        public MyOrientoinListener(Context context, int rate) {
            super(context, rate);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            int screenOrientation = getResources().getConfiguration().orientation;
            if (((orientation >= 0) && (orientation < 45)) || (orientation > 315)) {//设置竖屏
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            } else if (orientation > 225 && orientation < 315) { //设置横屏
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else if (orientation > 45 && orientation < 135) {// 设置反向横屏
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                }
            } else if (orientation > 135 && orientation < 225) {
                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                }
            }
        }
    }*/
}
